package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有
        List<CategoryEntity> entities = baseMapper.selectList(null);//没有查询条件就是查询所有
        //递归填充孩子
        return entities.stream()
                .filter(o -> o.getParentCid() == 0)
                .peek(o -> o.setChildren(getChildren(o, entities)))
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        ArrayList<Long> path = new ArrayList<>();
        findParentPath(catelogId, path);
        Collections.reverse(path);
        return path;
    }

    @Transactional
    @Override
    @CacheEvict(cacheNames = "category", allEntries = true)
//    @Caching(evict = {
//            @CacheEvict(cacheNames = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(cacheNames = "category", key = "'getCatalogJson'")
//    })
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        String categoryName = category.getName();
        if (StringUtils.isNotEmpty(categoryName)) {
            categoryBrandRelationService.updateCategory(categoryName, category.getCatId());
        }
        //todo 未来级联更新
    }

    @Cacheable(cacheNames = "category", key = "#root.methodName",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return list(new LambdaQueryWrapper<CategoryEntity>()
                .eq(CategoryEntity::getParentCid, 0L));
    }

    @Override
    @Cacheable(cacheNames = "category", key = "#root.methodName")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> listAllCategoryEntities = list();
        List<CategoryEntity> categoryEntities = getCategoryEntitiesByParentCId(listAllCategoryEntities, 0L);
        return categoryEntities.stream().filter(category1Entity -> {
            List<CategoryEntity> category2Entities = getCategoryEntitiesByParentCId(listAllCategoryEntities, category1Entity.getCatId());
            if (category2Entities == null) {
                return false;
            }
            category1Entity.setChildren(category2Entities);
            return true;
        }).collect(Collectors.toMap(category1Entity -> category1Entity.getCatId().toString(),
                category1Entity -> {
            List<CategoryEntity> category2Entities = category1Entity.getChildren();
                    return category2Entities.stream().map(category2Entity -> {
                    List<CategoryEntity> category3Entities =
                            getCategoryEntitiesByParentCId(listAllCategoryEntities, category2Entity.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (category3Entities != null) {
                        catalog3Vos = category3Entities.stream().map(category3Entity ->
                                new Catalog2Vo.Catalog3Vo(category3Entity.getParentCid().toString(),
                                        category3Entity.getCatId().toString(),
                                        category3Entity.getName())).collect(Collectors.toList());

                    }
                    return new Catalog2Vo(category2Entity.getParentCid().toString(),
                            catalog3Vos,
                            category2Entity.getCatId().toString(),
                            category2Entity.getName());
                }).collect(Collectors.toList());
        }));
    }

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        //1.加入缓存
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            return getCatalogJsonFromDbWithRedissonLock();
        }
        return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this) {
            return getDataFormDb();
        }
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("CatalogJson-Lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFormDb;
        try {
            dataFormDb = getDataFormDb();
        } finally {
            lock.unlock();
        }
        return dataFormDb;
    }

    private Map<String, List<Catalog2Vo>> getDataFormDb() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isNotEmpty(catalogJSON)) {
            return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
        }
        List<CategoryEntity> listAllCategoryEntities = list();
        List<CategoryEntity> categoryEntities = getCategoryEntitiesByParentCId(listAllCategoryEntities, 0L);
        Map<String, List<Catalog2Vo>> map = categoryEntities.stream().filter(category1Entity -> {
            List<CategoryEntity> category2Entities = getCategoryEntitiesByParentCId(listAllCategoryEntities, category1Entity.getCatId());
            if (category2Entities == null) {
                return false;
            }
            category1Entity.setChildren(category2Entities);
            return true;
        }).collect(Collectors.toMap(category1Entity -> category1Entity.getCatId().toString(),
                category1Entity -> {
                    List<CategoryEntity> category2Entities = category1Entity.getChildren();
                    return category2Entities.stream().map(category2Entity -> {
                        List<CategoryEntity> category3Entities =
                                getCategoryEntitiesByParentCId(listAllCategoryEntities, category2Entity.getCatId());
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                        if (category3Entities != null) {
                            catalog3Vos = category3Entities.stream().map(category3Entity ->
                                    new Catalog2Vo.Catalog3Vo(category3Entity.getParentCid().toString(),
                                            category3Entity.getCatId().toString(),
                                            category3Entity.getName())).collect(Collectors.toList());

                        }
                        return new Catalog2Vo(category2Entity.getParentCid().toString(),
                                catalog3Vos,
                                category2Entity.getCatId().toString(),
                                category2Entity.getName());
                    }).collect(Collectors.toList());
                }));
        String jsonString = JSON.toJSONString(map);
        stringRedisTemplate.opsForValue().set("catalogJSON", jsonString, 1, TimeUnit.DAYS);
        return map;
    }

    private List<CategoryEntity> getCategoryEntitiesByParentCId(List<CategoryEntity> listAllCategoryEntities, Long parentCId) {
        return listAllCategoryEntities.stream()
                .filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), parentCId))
                .collect(Collectors.toList());
    }

    /**
     * 递归设置父子路径
     */
    private void findParentPath(Long catelogId, ArrayList<Long> path) {
        path.add(catelogId);
        CategoryEntity byId = getById(catelogId);
        Long parentCid = byId.getParentCid();
        if (Objects.nonNull(parentCid) && parentCid != 0) {
            findParentPath(parentCid, path);
        }
    }

    /**
     * 递归设置孩子
     */
    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> entities) {
        return entities.stream()
                .filter(o -> Objects.equals(entity.getCatId(), o.getParentCid()))
                .peek(o -> o.setChildren(getChildren(o, entities)))
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
    }

}